<?php

/**
 * 友情链接管理
 */
namespace app\ph\controller;

class Link extends Base
{
    protected $link_model;

    public function __construct()
    {
        parent::__construct();
        $this->link_model = new \app\common\model\Link();
    }

    /**
     * 列表
     * @return \think\response\View
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data = $this->link_model->getList([]);
        $page = $data->render();
        $data = $data->items();
        return view('link/index', ['data' => $data, 'page' => $page]);
    }

    /**
     * 添加 视图
     * @return \think\response\View
     */
    public function data_insert()
    {
        return view('link/data_insert');
    }

    /**
     * 修改
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function data_update($id)
    {
        if (!$id) {
            $this->error('缺失参数');
        }
        $data = $this->link_model->getOne(['id' => $id], '*', 'id desc');
        if (!$data) {
            $this->error('数据获取失败');
        }
        return view('link/data_update', ['data' => $data]);
    }

    /**
     * 添加/修改 操作
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function data_save()
    {
        $data['title']  = input('post.title');
        $data['link']   = input('post.link');
        $data['num']    = input('post.num');
        $data['status'] = input('post.status');
        $id             = input('post.id');

        $validate = new \app\common\validate\Link;
        if (!$validate->check($data)) {
            return json(['code' => 100, 'message' => $validate->getError()]);
        }

        if ($id) {
            $res = $this->link_model->editData(['id' => $id], $data);
        } else {
            $res = $this->link_model->addData($data);
        }
        return operationResult($res, url("Link/index"));
    }


    /**
     * 删除
     * @return \think\response\Json
     */
    public function data_delete()
    {
        $id = input('post.id');
        if (!$id) {
            return json(['code' => 100, 'msg' => '缺少参数ID']);
        }
        $res = $this->link_model->dataDelete($id);
        return operationResult($res);
    }

    /**
     * 清除缓存
     */
    public function data_clear()
    {
        cache("link", null);
        $this->success("清除成功");
    }
}
